define(function (require, exports, module) {
    'use strict';
    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        notify = require('js/utils/notify'),
        models = require('js/apps/op/models'),
        utils = require('js/utils/tools'),
        tz = require('js/utils/tz'),
        moment = require('moment'),
        app = Backbone.history;
    require('datetimepicker');
    var ActivityOrderListView = Backbone.View.extend({
        tagName: "div",
        events: {
            'click #search': 'doSearch',
            'change #selectAll': 'selectAll',
            'change .check-row': 'checkRow',
            'click #refundOrder': 'refundOrder',
        },
        initialize: function (options) {
            this.options = options;
            this.options.$size = 30;
            this.collection = new models.ActivityOrderCollection();
            this.collection.bind('change reset remove', this.renderWithData, this);
            this.checkedIds = [];
        },
        render: function () {
            this.$el.html("");
            $(window).scrollTop(0);
            return this;
        },
        refundOrder: function () {
          var that = this;
          $.post('/admin/activity/' + this.options.activity_type + '/order/refund/', JSON.stringify({
            ids: this.checkedIds
          })).done(function (resp) {
              var data = resp.data;
              notify.success('提示', '成功退单' + data.succ_list.length + '个！');
              that.load();
          }).fail(function (data) {
              notify.notifyResp(data);
          });
        },
        selectAll: function (e) {
            var checked = $(e.target).is(':checked');
            $('.check-row').prop('checked', checked);
            if (!checked) {
                this.checkedIds = [];
            } else {
                this.checkedIds = this.collection.pluck('id');
            }
            $('#selectTips').html('已选中' + this.checkedIds.length + '个');
        },
        checkRow: function (e) {
            var tr = $(e.target).closest('tr'),
                id = tr.data('id');
            if ($(e.target).is(':checked')) {
                this.checkedIds.push(id);
            } else {
                this.checkedIds = _.without(this.checkedIds, id);
            }
            $('#selectTips').html('已选中' + this.checkedIds.length + '个');
        },
        doSearch: function () {
            var options = {},
                searched = {};
            searched.user_id = $('#searchUid').val();
            searched.track_id = $('#searchTrackId').val();
            searched.activity_type = parseInt($("#searchActivityType").val());
            searched.status = parseInt($("#searchStatus").val());
            searched.term_lower = $("#searchTermLower").val();
            searched.term_upper = $('#searchTermUpper').val();
            searched.price_lower = $("#searchPriceLower").val();
            searched.price_upper = $("#searchPriceUpper").val();
            searched.win_price_lower = $("#searchWinPriceLower").val();
            searched.win_price_upper = $("#searchWinPriceUpper").val();
            if (searched.user_id) {
                options.user_id = searched.user_id;
            }
            if (searched.track_id) {
                options.track_id = searched.track_id;
            }
            options.activity_type = searched.activity_type;
            if (searched.status != -1) {
                options.status = searched.status;
            }
            if (searched.term_lower || searched.term_upper) {
                options.term = {};
                if (searched.term_lower) options.term.$gte = searched.term_lower;
                if (searched.term_upper) options.term.$lte = searched.term_upper;
            }
            if (searched.price_lower || searched.price_upper) {
                options.price = {};
                if (searched.price_lower) options.price.$gte = parseInt(searched.price_lower);
                if (searched.price_upper) options.price.$lte = parseInt(searched.price_upper);
            }
            if (searched.win_price_lower || searched.win_price_upper) {
                options.win_price = {};
                if (searched.win_price_lower) options.win_price.$gte = parseInt(searched.win_price_lower);
                if (searched.win_price_upper) options.win_price.$lte = parseInt(searched.win_price_upper);
            }
            searched.created_at_lower = $("#searchCreatedAtLower").val();
            searched.created_at_upper = $('#searchCreatedAtUpper').val();
            if (searched.created_at_lower || searched.created_at_upper) {
                options.created_at = {};
                if (searched.created_at_lower) options.created_at.$gte = searched.created_at_lower;
                if (searched.created_at_upper) options.created_at.$lt = searched.created_at_upper;
            }
            utils.saveSearched('op/activity_order', searched);
            app.navigate(utils.composeQueryString('#op/activity_order/', options), {
                trigger: true
            });
        },
        renderWithData: function () {
            this.$el.html(this.template({
                items: this.collection.toJSON(),
                searched: utils.getSearched('op/activity_order')
            }));
            var that = this;
            $('.refreshStatus').click(function() {
                var data_id = $(this).data('id');
                $.post('/admin/activity/' + that.options.activity_type + '/order/'+data_id+'/fresh/').done(function (resp) {
                  var data = resp.data;
                  if (data.award) {
                      notify.success('提示', '补发金额'+ data.award +'成功！');
                  } else {
                      notify.success('提示', '无需补发');
                  }
                  that.load();
                }).fail(function (data) {
                  notify.notifyResp(data);
                });
            });
            utils.renderTable('main-list', {
                $orderby: that.options.$orderby || 'id',
                sortCallback: function (field) {
                    that.options.$orderby = field;
                    that.options.$page = 1;
                    var newUrl = utils.composeQueryString('#op/activity_order/', that.options);
                    app.navigate(newUrl, {
                        trigger: true
                    });
                }
            });
            $('[data-type=date]').datetimepicker({
                defaultDate: false,
                format: 'YYYY-MM-DD HH:mm:ss'
            });
            utils.getPaginator(that.options, this.collection.total, '#op/activity_order/');

            return this;
        },
        load: function () {
            this.collection.fetch({
                url: "/admin/activity/" + this.options.activity_type + "/order/",
                reset: true,
                data: this.options,
                error: function (c, r, o) {
                    notify.notifyResp(r);
                },
            });
        }
    });
    exports.List = Backbone.View.extend({
        el: "#content_wrapper",
        template: "op/ActivityOrderList.html",

        initialize: function (options) {
            this.options = options;
        },
        render: function () {
            if (!this.options.activity_type) this.options.activity_type = 1;
            var view = new ActivityOrderListView(this.options);
            view.template = this.template;

            this.$el.empty();
            this.$el.append(view.render().el);
            view.load();

            return this;
        }
    });

});
